<?php
namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Redis;
use App\Models\Users;
use App\Models\Linkslists;
use App\Models\Linkslistssetting;
use App\Models\Memberorders;
use App\Models\Linksrecord;
use App\Models\Linkslistsqrcodes;
use App\Models\Worklink;
use App\Models\Workqrcode;
use App\Models\Worklinkrecord;
use App\Models\Workqrcodeimg;
use App\Services\CacheService;
use App\Services\OutputService;
use App\Services\CallbackService;
use App\Models\Worklinkurl;
use Exception,Log;

class KefuController extends Controller
{
    public function wxkfStat(Request $request)
    {
        // try {
            $kfid = $request->kfid;
            $record_id = $request->record_id;
            $sign = md5("tt".$request->iv.$kfid.$request->iv."wl");
            if ($request->sign != $sign) return OutputService::error("接口参数错误");
            $workLink = Cache::get("work_link_".$kfid);
            if(empty($workLink)) {
                $workLinks = Worklink::workLinkDetial($kfid);
                if (empty($workLinks)) return OutputService::error("您访问的链接不存在！");
                $workLink = ["disable"=>$workLinks->disable,"limit_left"=>$workLinks->limit_left,"limit_pv"=>$workLinks->limit_pv,"limit_time"=>$workLinks->limit_time,"status"=>$workLinks->status,"corp_id"=>$workLinks->corp_id,"link_url"=>$workLinks->link_url];
                // 每次调用缓存30分钟
                Cache::put('work_link_'.$kfid,$workLink,1800);
            }

            if ($workLink["disable"] != 1) return OutputService::error("链接已删除,暂时无法访问！");
            if ($workLink["limit_left"] <= 0) return OutputService::error("链接访问次数不足,请充值后访问！");
            if ($workLink["limit_time"] < time()) {
                if ($workLink["limit_pv"] > 100) return OutputService::error("会员已过期,请续费后访问充值！");
                if ($workLink["limit_pv"] <= 100) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            }
            $from = empty($request->from) ? "other" : $request->from;
            if ($from == "dycard" && $workLink["limit_pv"] == 50000) {
                return OutputService::error("抖音卡片必须开通商家版以上会员!");
            }

            $ip = $request->ip;
            if (empty($ip)) {
                $ip = isset($_SERVER["HTTP_ALI_CDN_REAL_IP"]) ? $_SERVER["HTTP_ALI_CDN_REAL_IP"] : $_SERVER["REMOTE_ADDR"];
            }
            $code = empty($request->code) ? "" : $request->code;
            $province = mb_substr($request->province, 0, 9);
            $city = mb_substr($request->city, 0, 14);
            $district = mb_substr($request->district, 0, 14);
            // 增加页面访问PV
            $currentTime = time();
            Redis::hincrby('work_page_view_'.date("Ymd",$currentTime),$kfid,1);
            // 添加网页访问记录
            $workLinkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
            $workLinkRecord->creatWorkLinkRecordWeb($record_id,$kfid,$province,$city,$district,$request->system,$request->device,$request->browser,$ip,$code,$currentTime,$request->clickid,$request->adid,$request->back_platfrom);

            $paramas = urlencode(json_encode(["kfid"=>$kfid,"record_id"=>$record_id,"back_platfrom"=>$request->back_platfrom]));
            if (empty($workLink["corp_id"])) {
                $workLinkUrls = Cache::get('work_link_url');
                if(empty($workLinkUrls)) {
                    $workLinkUrl = Worklinkurl::getWorkLinkUrl();
                    if (empty($workLinkUrl)) return OutputService::error("当前暂无公用客服,请联系客服为您处理！");
                    $workLinkUrls = $workLinkUrl->pluck("link_url")->all();
                    // 每次调用缓存30分钟
                    Cache::put('work_link_url',$workLinkUrls,1800);
                }
                $link_key = rand(0,count($workLinkUrls)-1);
                $link_url = $workLinkUrls[$link_key]."&scene_param=".$paramas;
            } else {
                $link_url = $workLink["link_url"]."&scene_param=".$paramas;
            }
            return OutputService::success("SUCCESS",["link_url"=>$link_url]);
        // } catch (Exception $e) {
        //     return OutputService::error("接口异常,请稍后尝试!");
        // }
    }

    public function wxkfClick(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $record_id = $request->record_id;
        $kfid = $request->kfid;
        $today = date("Ymd",time());
        Redis::hincrby('work_click_'.$today,$kfid,1);
        $linkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
        $linkRecord->updateWorkLinkClickTime($record_id,time());
        return OutputService::success("Success");
    }

    public function workQrcodePress(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $kfid = $request->kfid;
        $record_id = $request->record_id;
        $today = date("Ymd",time());
        Redis::hincrby('work_qrcode_press_'.$today,$kfid,1);
        if (!empty($request->back_platfrom)) {
            CallbackService::wxkfCallBack($kfid,$record_id,"press",$request->back_platfrom);
        } else {
            $linkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
            $linkRecord->updateWorkLinkQrcodePress($record_id,time());
        }
        return OutputService::success("Success");
    }

    public function workQrcodePressCard(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $kfid = $request->kfid;
        $record_id = $request->record_id;
        $today = date("Ymd",time());
        Redis::hincrby('work_qrcode_press_card_'.$today,$kfid,1);
        if (!empty($request->back_platfrom)) {
            CallbackService::wxkfCallBack($kfid,$record_id,"press_card",$request->back_platfrom);
        } else {
            $linkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
            $linkRecord->updateWorkLinkQrcodePressCard($record_id,time());
        }
        return OutputService::success("Success");
    }

    public function workQrcode(Request $request)
    {
        if (empty($request->kfid)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $kfid = $request->kfid;
        $record_id = $request->record_id;
        $workQrcode = Cache::get('work_qrcode_'.$kfid);
        if(empty($workQrcode)) {
            $workLink = Worklink::workLinkDetial($kfid);
            if (empty($workLink)) return OutputService::error("您访问的链接不存在！");
            if ($workLink->disable != 1) return OutputService::error("链接已删除,暂时无法访问！");
            if ($workLink->limit_left <= 0) return OutputService::error("链接访问次数不足,请充值后访问！");
            if ($workLink->limit_pv > 100 && $workLink->limit_time < time()) return OutputService::error("会员已过期,请续费后访问充值！");
            if ($workLink->limit_pv < 100 && $workLink->limit_time < time()) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            // 获取小程序内样式
            $workQrcode = Workqrcode::apiWorkQrcode($kfid);
            $workQrcode = ["qrcode_switch"=>$workQrcode->switch,"qrcode_upper"=>$workQrcode->upper,"qrcode_daily"=>$workQrcode->daily,"qrcode_title"=>$workQrcode->qrcode_title,"qrcode_style"=>$workQrcode->qrcode_style,"qrcode_nike"=>$workQrcode->qrcode_nike,"qrcode_head_img"=>$workQrcode->qrcode_head_img,"qrcode_describe"=>$workQrcode->qrcode_describe,"qrcode_notice"=>$workQrcode->qrcode_notice,"device_bind"=>$workQrcode->device_bind];
            // 每次调用缓存30分钟
            Cache::put('work_qrcode_'.$kfid,$workQrcode,1800);
        }
        $batch = date("Ymd");
        $qrcodes = Redis::hget("work_link_qrcode_".$batch, $kfid);
        if (empty($qrcodes)) {
            // 更新昨天二维码数据并且删除缓存
            CacheService::removeWorkLinkQrcodeCache($kfid,date("Ymd",strtotime("-1 day")));
            $qrcodes = Workqrcodeimg::getAllWorkQrcodeImg($kfid);
            foreach ($qrcodes as $qrcode) {
                $qrcode->today = 0;
            }
            if (empty($qrcodes)) return OutputService::error("当前暂无二维码！");
            Redis::hset("work_link_qrcode_".$batch, $kfid, json_encode($qrcodes));
        } else {
            $qrcodes = json_decode($qrcodes);
        }
        $qrcode_image = "";
        $qrcode_id = "";
        if ($workQrcode["qrcode_switch"] == 2){
            // 随机二维码
            $key = rand(0,count($qrcodes)-1);
            $qrcodes[$key]->scan_total += 1;
            $qrcodes[$key]->scan_today += 1;
            $qrcode_image = $qrcodes[$key]->img_url;
            $qrcode_id = $qrcodes[$key]->id;
        } else {
            $qrcodes = collect($qrcodes);
            if ($workQrcode["qrcode_switch"] == 1) {
                // 顺序切换
                $qrcodes = $qrcodes->sortByDesc('rate')->all();
            } else {
                // 循环切换
                $qrcodes = $qrcodes->sortBy('scan_today')->all();
            }
            foreach ($qrcodes as $key => $qrcode) {
                if ($workQrcode["qrcode_upper"] == 1) {
                    // 累计上限
                    if ($qrcode->scan_total < $qrcode->count_limit) {
                        $qrcodes[$key]->scan_total += 1;
                        $qrcodes[$key]->scan_today += 1;
                        $qrcode_image = $qrcode->img_url;
                        $qrcode_id = $qrcode->id;
                        break;
                    }
                } else {
                    // 每日上限
                    if ($qrcode->scan_today < $workQrcode["qrcode_daily"]) {
                        $qrcodes[$key]->scan_total += 1;
                        $qrcodes[$key]->scan_today += 1;
                        $qrcode_image = $qrcode->img_url;
                        $qrcode_id = $qrcode->id;
                        break;
                    }
                }
            }
        }
        if (empty($qrcode_image)) {
            // 当前暂无二维码,启动保底
            $qrcodes[0]->scan_total += 1;
            $qrcodes[0]->scan_today += 1;
            $qrcode_image = $qrcodes[0]->img_url;
            $qrcode_id = $qrcodes[0]->id;
        };
        Redis::hset("work_link_qrcode_".$batch, $kfid, json_encode($qrcodes));

        $today = date("Ymd",time());
        Redis::hincrby('work_qrcode_show_'.$today,$kfid,1);
        $linkRecord = new Worklinkrecord(["tbnum"=>$record_id[0]]);
        $linkRecord->updateWorkLinkQrcodeShow($record_id,time(),$qrcode_id);

        $workQrcode["img_url"] = $qrcode_image;
        return OutputService::success("Success",$workQrcode);
    }

    public function kefuQrcodePress(Request $request)
    {
        if (empty($request->links_id)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $links_id = $request->links_id;
        $record_id = $request->record_id;
        $today = date("Ymd",time());
        Redis::hincrby('mini_activate_'.$today,$links_id,1);
        $linkRecord = new Linksrecord(["tbnum"=>$record_id[0]]);
        $linkRecord->updateLinkQrcodePress($record_id,time());
        return OutputService::success("Success");
    }

    public function kefuQrcodeDetial(Request $request)
    {
        if (empty($request->links_id)) return OutputService::error("参数错误!");
        if (empty($request->record_id)) return OutputService::error("参数错误!");
        $links_id = $request->links_id;
        $record_id = $request->record_id;
        if(Cache::has('links_api_'.$links_id)) {
            $links = Cache::get('links_api_'.$links_id);
        } else {
            $links = Linkslists::jumpGetApiLinks($links_id);
            if (empty($links)) return OutputService::error("您访问的链接不存在！");
            if ($links->disable != 1) return OutputService::error("链接已删除！");
            if (!in_array($links["platfrom_type"], [8,9,11,12])) return OutputService::error("链接错误！");
            if ($links->limit_status == 1 && $links->left_pv <= 0) return OutputService::error("链接访问次数不足,请充值！");
            if ($links->limit_pv > 1000 && $links->end_time < time()) return OutputService::error("会员已过期,请续费后访问充值！");
            if ($links->limit_pv < 1000 && $links->end_time < time()) return OutputService::error("免费体验已过期1小时,请开通会员后访问！");
            // 获取小程序内样式
            $linksSetting = Linkslistssetting::getLinksListsSetting($links_id);
            $links = collect($links)->merge($linksSetting)->all();
            // 每次调用缓存30分钟
            Cache::put('links_api_'.$links_id, $links, 1800);
        }

        if (in_array($links["platfrom_type"], [8,9,11,12])) {
            $batch = date("Ymd");
            $qrcodes = Redis::hget("links_qrcodes_".$batch, $links_id);
            if (empty($qrcodes)) {
                // 更新昨天二维码数据并且删除缓存
                CacheService::removeLinksQrcodeCache($links_id,date("Ymd",strtotime("-1 day")));
                $qrcodes = Linkslistsqrcodes::getAllLinksListsQrcodes($links_id);
                if (empty($qrcodes)) return OutputService::error("当前暂无二维码！");
                Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));
            } else {
                $qrcodes = json_decode($qrcodes);
            }
            $qrcode_image = "";
            $qrcodes_id = "";
            if (empty($qrcodes)) return OutputService::error("当前暂无二维码！");
            if ($links["qrcode_switch"] == 2){
                // 随机二维码
                $key = rand(0,count($qrcodes)-1);
                $qrcodes[$key]->scan_total += 1;
                $qrcodes[$key]->scan_today += 1;
                $qrcode_image = $qrcodes[$key]->img_url;
                $qrcodes_id = $qrcodes[$key]->qrcodes_id;
            } else {
                $qrcodes = collect($qrcodes);
                if ($links["qrcode_switch"] == 1) {
                    // 顺序切换
                    $qrcodes = $qrcodes->sortByDesc('rate')->all();
                } else {
                    // 循环切换
                    $qrcodes = $qrcodes->sortBy('scan_today')->all();
                }
                foreach ($qrcodes as $key => $qrcode) {
                    if ($links["qrcode_upper"] == 1) {
                        // 累计上限
                        if ($qrcode->scan_total < $qrcode->count_limit) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            $qrcodes_id = $qrcode->qrcodes_id;
                            break;
                        }
                    } else {
                        // 每日上限
                        if ($qrcode->scan_today < $links["qrcode_daily"]) {
                            $qrcodes[$key]->scan_total += 1;
                            $qrcodes[$key]->scan_today += 1;
                            $qrcode_image = $qrcode->img_url;
                            $qrcodes_id = $qrcode->qrcodes_id;
                            break;
                        }
                    }
                }
            }
            if (empty($qrcode_image)) return OutputService::error("当前暂无二维码！");
            Redis::hset("links_qrcodes_".$batch, $links_id, json_encode($qrcodes));

            $today = date("Ymd",time());
            Redis::hincrby('mini_view_'.$today,$links_id,1);
            $linkRecord = new Linksrecord(["tbnum"=>$record_id[0]]);
            $linkRecord->updateLinkQrcodeShow($record_id,time(),$qrcodes_id);
        }

        $nlinks = ["title"=>"二维码详情","miniapp_style"=>$links["miniapp_style"],"qrcode_notice"=>$links["qrcode_notice"],"logo"=>$links["logo"],"nike"=>$links["nike"],"describe"=>$links["describe"],"platfrom_type"=>$links["platfrom_type"],"qrcodes_img_url"=>$qrcode_image];
        return OutputService::success("Success",$nlinks);
    }
}